<?php
/*
 * @Author: 孙开源 && sunkaiyuan@namenode.cn
 * @Date: 2023-04-12 16:45:39
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @LastEditTime: 2023-04-12 17:12:30
 * @Description: 
 * 
 */namespace zhijingfeisuo\Kernel\Responses;

use GuzzleHttp\Psr7\Response as GuzzleResponse;
use zhijingfeisuo\Kernel\Support\Collection;
use Psr\Http\Message\ResponseInterface;

class Response extends GuzzleResponse
    {
    /**
     * @return string
     */
    public function getBodyContents() : string
        {
        $this->getBody()->rewind();
        $contents = $this->getBody()->getContents();
        $this->getBody()->rewind();

        return $contents;
        }

    /**
     * @param \Psr\Http\Message\ResponseInterface $response
     *
     * @return \zhijingfeisuo\Kernel\Responses\Response
     */
    public static function buildFromPsrResponse(ResponseInterface $response) : self
        {
        return new static(
            $response->getStatusCode(),
            $response->getHeaders(),
            $response->getBody(),
            $response->getProtocolVersion(),
            $response->getReasonPhrase()
        );
        }

    /**
     * Build to json.
     *
     * @return string
     */
    public function toJson() : string
        {
        return json_encode($this->toArray());
        }

    /**
     * Build to array.
     *
     * @return array
     */
    public function toArray() : array
        {
  
        $array = json_decode($this->getBodyContents(), true);

        if (JSON_ERROR_NONE === json_last_error()) {
            return (array) $array;
            }

        return [];
        }

    /**
     * Get collection data.
     *
     * @return \zhijingfeisuo\Kernel\Support\Collection
     */
    public function toCollection() : \zhijingfeisuo\Kernel\Support\Collection
        {
        return new Collection($this->toArray());
        }

    /**
     * @return object
     */
    public function toObject() : object
        {
        return json_decode($this->getBodyContents());
        }

    /**
     * @return string
     */
    public function __toString() : string
        {
        return $this->getBodyContents();
        }
    }